package com.example.chengzhengwei;

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TtySerialPortHelper {
    private static final String TAG = "SPortHelper";
    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
    private volatile boolean mIsOpen = false;
    private final Context mContext;
    private SerialPortHelper mSerialPortHelper;
    private OnDataReceivedListener mDataListener;

    public TtySerialPortHelper(Context context) {
        this.mContext = context.getApplicationContext();
        initSerialHelper();
    }

    private void initSerialHelper() {
        mSerialPortHelper = new SerialPortHelper(mContext);
        mSerialPortHelper.setListener(new SerialPortHelper.SerialPortListener() {
            @Override
            public void onConnected() {
                mIsOpen = true;
                Log.d(TAG, "Serial port connected");
            }

            @Override
            public void onDisconnected() {
                mIsOpen = false;
                Log.d(TAG, "Serial port disconnected");
            }

            @Override
            public void onError(String message) {
                Log.e(TAG, "Serial port error: " + message);
            }

            @Override
            public void onDataReceived(byte[] data) {
                if (mDataListener != null) {
                    mDataListener.onDataReceived(data);
                }
            }
        });
        mSerialPortHelper.init();
    }

    public void openAsync(SerialOpenCallback callback) {
        mExecutor.execute(() -> {
            try {
                if (!mIsOpen) {
                    mSerialPortHelper.connect();
                    // 等待连接状态更新
                    int retry = 0;
                    while (!mIsOpen && retry < 10) {
                        Thread.sleep(100);
                        retry++;
                    }

                    if (mIsOpen && callback != null) {
                        callback.onOpenSuccess();
                    } else if (!mIsOpen && callback != null) {
                        callback.onOpenError(new IOException("Failed to open serial port"));
                    }
                } else if (callback != null) {
                    callback.onOpenSuccess();
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onOpenError(e);
                }
            }
        });
    }

    public void close() {
        mExecutor.execute(() -> {
            if (mIsOpen) {
                mSerialPortHelper.disconnect();
                mIsOpen = false;
            }
        });
    }

    public boolean isOpen() {
        return mIsOpen;
    }

    public int write(byte[] data) throws Exception {
        if (!mIsOpen) {
            throw new IOException("Serial port is not open");
        }
        mSerialPortHelper.sendBytes(data); // 假设已在 SerialPortHelper 中添加此方法
        return data.length;
    }

    public void writeAsync(byte[] data, SerialWriteCallback callback) {
        mExecutor.execute(() -> {
            try {
                int bytesWritten = write(data);
                if (callback != null) {
                    callback.onWriteComplete(bytesWritten);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onWriteError(e);
                }
            }
        });
    }

    public void setOnDataReceivedListener(OnDataReceivedListener listener) {
        this.mDataListener = listener;
    }

    public void shutdown() {
        close();
        mExecutor.shutdown();
    }

    // 在 SerialPortHelper 中添加此方法
    /*
    public void sendBytes(byte[] data) {
        if (!isConnected) {
            if (listener != null) listener.onError("串口未连接");
            return;
        }
        if (ioManager != null) {
            ioManager.writeAsync(data);
        }
    }
    */

    // 回调接口定义
    public interface SerialOpenCallback {
        void onOpenSuccess();
        void onOpenError(Exception e);
    }

    public interface SerialWriteCallback {
        void onWriteComplete(int bytesWritten);
        void onWriteError(Exception e);
    }

    public interface OnDataReceivedListener {
        void onDataReceived(byte[] data);
    }
}